import { host } from './conf'

function formatNumber (n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

function formatTime (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}

function currentPage () {

  var pages = getCurrentPages(),
    thisPage = pages[pages.length - 1],
    pagePath = thisPage.__route__;

  //__route__中存储的路径前加 '/'
  if (pagePath.indexOf('/') != 0) {
    pagePath = '/' + pagePath
  }

  return pagePath;
}

//是否授权
function isAuth (callBack) {
  wx.getSetting({
    success: function (res) {
      var auth = false;
      if (res.authSetting['scope.userInfo']) {
        auth = true  //已经授权
      }
      callBack(auth)
    },
    fail: function (e) {
      console.log('isAuth-error:' + e)
    }
  })
}

//异步接口
function request (obj) {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: host + obj.url,
      data: obj.data,
      // header: { 'content-type': 'application/x-www-form-urlencoded'},
      method: obj.type ? obj.type : 'GET',
      success (res) {
        resolve(res.data)
      },
      fail (e) {
        reject(e)
      }
    })
  })
}

//上传图片
function uploadFile (imgList) {
  if (imgList && imgList.length > 0) {
    wx.uploadFile({
      url: host + '/GroupBuyBackendV1/api/uploadFile',
      filePath: imgList[0],
      name: 'file',
      header: { 'content-type': 'multipart/form-data'},
      success (res) {
        imgList.splice(0, 1);
        uploadFile(imgList);
      }
    })
  }
}

//时间间隔 传几天
function latterTime (d) {
  var time = new Date()
  var endTime = new Date(time.getTime() + d*60*60*24*1000)
  var year = endTime.getFullYear()
  var month = endTime.getMonth() + 1
  var day = endTime.getDate()

  return `${year}-${month > 9 ? month : '0' + month}-${day > 9 ? day : '0' + day}`
}

//拼接图片 arr图片数组， len要获取的长度，没有则都返回
function imagesLink (arr, len) {
  if (arr && arr.length) {
    var resArr = []
    arr.forEach(function(item) {
      if (item.indexOf('https://') == 0 || item.indexOf('http://') == 0) {
        resArr.push(item)
      } else {
        resArr.push(host + '/wetousuPhoto/' + item)
      }
    })

    if (len && len < resArr.length) {
      resArr.length = len
    }
    return resArr
  }
}
//将时间戳格式化yyyy-mm-dd
function timeStamp (str) {
  if (str && (str = str + '')) {
    
    if (str.indexOf('-') == -1) {
      var str = parseInt(str)
    }
    var time = new Date(str)
    var year = time.getFullYear()
    var month = time.getMonth() + 1
    var day = time.getDate()

    return `${year}-${month > 9 ? month : '0'+ month}-${day > 9 ? day : '0'+ day}`
  }
}
//判断传入的时间和当前时间
function overNowTime (time) {
  if (time) {
    (time.indexOf('-') == -1) && parseInt(time)
    var timer = new Date(time).getTime()
    var nowTime = new Date().getTime()
   
    if (timer < nowTime) {
      return true
    } else {
      return false
    }
  }
}
/**
 * 本地存储用户信息
 */
async function setUserInfoToStorage (uinfo) {
  var user = {}
  var openId = wx.getStorageSync('openId')
  var userInfo = wx.getStorageSync('userInfo')

  if (userInfo) {
    userInfo = JSON.parse(userInfo)
    if (userInfo && userInfo.name && userInfo.address && userInfo.mobile) {
      return
    }
  }
  
  user = await request({
    url: '/GroupBuyBackendV1/getUserByOpenId/' + openId
  })

  if (user && user.userId) {
    var info = await request({
      url: '/GroupBuyBackendV1/user/'+ user.userId
    })
    if (info.name && info.address && info.mobile) {
      var userData = {
        name: info.name,
        mobile: info.mobile,
        address: info.address
      }
    } else {
      user = await request({
        url: '/GroupBuyBackendV1/user',
        type: 'POST',
        data: {
          openId: openId,
          userInfo: JSON.stringify(uinfo),
          dateTime: new Date().getTime()
        }
      })
    }
  } else {
    user = await request({
      url: '/GroupBuyBackendV1/user',
      type: 'POST',
      data: {
        openId: openId,
        userInfo: JSON.stringify(uinfo),
        dateTime: new Date().getTime()
      }
    })
  }
  
  if (user.userId) {
    wx.setStorageSync('userId', user.userId)
    wx.setStorageSync('userIcon', uinfo.avatarUrl)
    wx.setStorageSync('userJson', JSON.stringify(uinfo))
  }
  if (typeof userData != 'undefined') {
    wx.setStorageSync('userInfo', JSON.stringify(userData))
  }
}
/**
 * 获取授权信息
 */
function getAuthInfo () {
  wx.getSetting({
    success: function (res) {
      //用户已经授权
      console.log(res.authSetting)
      if (res.authSetting['scope.userInfo']) {
        wx.getUserInfo({
          success (res) {
            setUserInfoToStorage(res.userInfo)
          }
        })
      } else {
        //未授权跳转登陆
        wx.navigateTo({
          url: '/pages/login/main'
        })
      }
    }
  })
}
/**
 * 获取openid
 */
async function getOpenId (wxcode) {
  var res = await request({
    url: '/GroupBuyBackendV1/getOpenId?js_code='+ wxcode
  })
  //openid大小写
  if (res && res.openid) {
    getAuthInfo()  //获取授权后的信息
    wx.setStorageSync('openId', res.openid)
  }
}
/**
 * 用户登陆方法
 */
function userLogin () {
  //是否有openId
  if (wx.getStorageSync('userId') && wx.getStorageSync('userInfo')) {
    return
  }
  if (wx.getStorageSync('openId')) {
    getAuthInfo()
  } else {
    wx.login({
      success (res) {
        if (res.code) {
          getOpenId(res.code)
        }
      },
      fail (e) {
        wx.showToast({
          icon: 'none',
          title: '登陆接口调用失败'
        })
      }
    })
  }
}

/**
 * @param {status} 状态
 * @param {type}   1：到货通知 2：发货通知
 */
function messageStatus (status, type) {
  var s = {
    a: '到货通知',
    b: '已通知',
    c: '发货',
    d: '已发货',
  }
  var res = "";
  (typeof type == 'number') && (type = type + '')
  switch (type) {
    case '1':
      if (status == s.b) {
        res = s.b
      } else {
        res = s.a
      }
      break;
    case '2':
      if (status == s.d) {
        res = s.d
      } else {
        res = s.c
      }
  }
  return res
}

/**
 * 数组按照时间戳排序
 *  key: 通过哪个字段判断默认值创建事件
 */
function timeSort (arr, key = 'createTime') {
  function times (index) {
    var val = arr[index][key]
    if (val && val.indexOf('-') == -1) {
      val = parseInt(val)
    }
    if (val) {
      return new Date(val).getTime()
    } else {
      return ''
    }
  }
  if (arr && arr.length) {
    for (var i = 0; i < arr.length - 1; i++) {
      for (var j = 0; j < arr.length - 1 - i; j++) {
        if (!arr[j] || times(j) < times(j+1)) {
          var tmp = arr[j]
          arr[j] = arr[j+1]
          arr[j+1] = tmp
        }
      }
    }
  }
}

/**
 * 分页方法 ，默认一页10条
 * @param {data} data原始数据 
 * @param {page} page获取第几页数据
 * @return {haveNext: true, data:[]}
 */
function paging (data, page = 1) {
  var pageSize = 10
  var res = {
      data: [],
      haveNext: false
  }
  if (data && data.length) {
    if (data.length <= pageSize) {
      res.data = data
      return res
    } else {
      if (page > 0) {
        var maxSize = Math.ceil(data.length/pageSize)
        if (page > maxSize) {
          return res
        } else {
          //根据page获取对应数据
          var begin = (page - 1) * 10
          var next = data.length > page * 10
          return {
            haveNext: next,
            data: data.slice(begin, begin + pageSize)
          }
        }
      } else {
        throw new error('page value != 0')
      }
    }
  }
}

export {
  isAuth,
  paging,
  request,
  timeSort,
  timeStamp,
  userLogin,
  imagesLink,
  latterTime,
  uploadFile,
  currentPage,
  overNowTime,
  messageStatus,
}
